package com.lou1052.core.base.thread;

import com.lou1052.core.base.Pool;

/**
 * 延迟的线程局部变量
 * 第一次调用时才从池中取出创建
 * Created with IntelliJ IDEA.
 * User: liuqing
 * To change this template use File | Settings | File Templates.
 */
public final class LazyPoolObjectThreadLocal<O> extends ThreadLocal<O>{

    private final Pool<O> pool;

    public LazyPoolObjectThreadLocal(Pool<O> pool) {
        this.pool = pool;
    }

    @Override
    public O get() {
        O object = super.get();
        if(object==null){//第一次调用get时 从池中取
            object = pool.borrow();
            super.set(object);//设置局部变量
        }
        return object;
    }

    @Override
    protected  O initialValue() {
        return null;
    }

    @Override
    public void remove() {
        O object = super.get();
        if(object!=null) {//放回池中
            pool.release(object);
        }
        super.remove();
    }

    @Override
    public  void set(O value) {
        //no set
    }
}